<template>
  <div class="MenuEdit">
    <el-form ref="EditFrom" :model.trim="imgTxtData" labelPosition="top" labelWidth="50px" :rules="rules">
      <el-form-item :label="$t('km.title')" prop="title">
        <el-input v-model="imgTxtData.title"></el-input>
      </el-form-item>
      <el-form-item :label="$t('configLazyLoad.channel.wexinTip73')" prop="author">
        <el-input v-model="imgTxtData.author"></el-input>
      </el-form-item>
      <el-form-item :label="$t('km.content')" prop="content">
        <div id="weixinEdit">
        </div>
      </el-form-item>
      <el-form-item :label="$t('configLazyLoad.channel.wexinTip74')" prop="content_source_url">
        <el-input v-model="imgTxtData.content_source_url"></el-input>
      </el-form-item>
    </el-form>
    <div class="secondArea">
      <h3>{{$t('configLazyLoad.channel.wexinTip75')}}</h3>
      <p>
        <strong>{{$t('configLazyLoad.channel.wexinTip76')}}</strong>
        <span class="pictips" style="margin-left: 20px">{{$t('configLazyLoad.channel.wexinTip77')}}</span>
      </p>
      <div style="margin: 10px 0;"><el-button class="primary_btn" id="WechatMenuImageFile">{{$t('configLazyLoad.channel.wexinTip78')}}</el-button></div>
      <div style="margin: 10px 0;"><img :src="imgUrl" v-show="imgUrl" class="uploadImg"> <span @click="deleteImg" class="deleteImg">{{$t('public.delete')}}</span></div>
      <el-checkbox v-model.trim="imgTxtData.show_cover_pic"  class="pictips">{{$t('configLazyLoad.channel.wexinTip79')}}</el-checkbox>
      <p style="margin: 10px 0">
        <strong>{{$t('configLazyLoad.channel.wexinTip80')}}</strong>
        <span class="pictips" style="margin-left: 20px">{{$t('configLazyLoad.channel.wexinTip81')}}</span>
      </p>
      <el-input type="textarea" :rows="4" :maxlength="120" v-model="imgTxtData.digest"></el-input>
    </div>
    <div class="footer">
      <el-button class="primary_btn" @click="cancel">{{$t('configLazyLoad.channel.wexinTip82')}}</el-button>
      <el-button class="primary_btn" type="primary" @click="save">{{$t('public.save')}}</el-button>
    </div>
  </div>
</template>

<script>
  import Editor from 'wangeditor'
  import {uploadTo7moorImDomain} from '@/utils/qiniuUtils'
  import {getCurrentDate, deepClone, isEmptyObj, filterXSS} from '@/utils/m7Utils'
  import {checkform} from '@/utils/validate'
  import * as uuid from 'uuid'
  export default {
    name: 'weixinEditDialog',
    data () {
      let checkUrl = (rule, value, callback) => {
        if (value === 'http://') {
          callback(new Error(this.$t('validate.required')))
        } else if (checkform(value, 'Url')) {
          callback(new Error(this.$t('configLazyLoad.channel.wexinTip37')))
        } else {
          callback()
        }
      }
      return {
        imgTxtData: {
          title: '',
          author: '',
          content: '',
          content_source_url: 'http://',
          digest: '',
          imgMediaId: '',
          show_cover_pic: false
        },
        imgUrl: '',
        trimTxt: '',
        rules: {
          title: [
            {required: true, message: this.$t('validate.required'), trigger: 'blur'},
            { max: 64, message: this.$t('configLazyLoad.channel.wexinTip83'), trigger: 'blur' }
          ],
          author: [
            {required: true, message: this.$t('validate.required'), trigger: 'blur'},
            { max: 8, message: this.$t('configLazyLoad.channel.wexinTip84'), trigger: 'blur' }
          ],
          content: [
            {required: true, message: this.$t('validate.required'), trigger: 'blur'}
          ],
          content_source_url: [
            {required: true, validator: checkUrl, trigger: 'blur'}
          ]
        },
        m7uploaders: []
      }
    },
    props: ['weixindata', 'imgdata'],
    methods: {
      save () {
        let rep = function (o) {
          let result = o.replace(/"/g, '&quot;').replace(/ /g, '&nbsp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
          return result
        }
        this.$refs.EditFrom.validate((valid) => {
          if (valid) {
            if (this.imgUrl === '') {
              this.$message.error(this.$t('configLazyLoad.channel.wexinTip85'))
              return
            }
            let titlerep = rep(this.imgTxtData.title)
            let authorrep = rep(this.imgTxtData.author)
            let digest = this.imgTxtData.digest === '' ? this.trimTxt.substr(0, 54) : this.imgTxtData.digest
            let digestrep = rep(digest)
            let data = {
              news: {
                'title': escape(escape(titlerep)),
                'thumb_media_id': this.imgTxtData.imgMediaId,
                'author': escape(escape(authorrep)),
                'digest': escape(escape(digestrep)),
                'show_cover_pic': this.imgTxtData.show_cover_pic ? 1 : 0,
                'content': escape(escape(this.imgTxtData.content)),
                'content_source_url': escape(escape(this.imgTxtData.content_source_url))
              },
              _id: this.weixindata._id,
              mediaId: ''
            }
            this.$store.dispatch('saveNewsMaterial', data).then((resp) => {
              if (resp.success) {
                let imgdata = deepClone(this.imgTxtData)
                imgdata.url = this.imgUrl
                if (resp.data.article_id) {
                  imgdata.article_id = resp.data.article_id
                }
                if (resp.data.media_id) {
                  imgdata.media_id = resp.data.media_id
                }
                imgdata.articleUrl = resp.data.url
                let data = {
                  flag: true,
                  imgTxt: imgdata
                }
                this.$emit('saveDone', data)
              }
            })
          }
        })
      },
      cancel () {
        this.$emit('cancel')
      },
      deleteImg () {
        this.imgUrl = ''
      },
      initUploadImageFile () {
        let account = this.$store.state.session.user.account
        let self = this
        let fileAdded = function (up, files) {
          console.log('fileAdd')
        }
        let beforeUpload = function (up, file) {
          console.log('beforeUpload1')
        }
        let uploadProgress = function (up, file) {
          console.log('uploadProgress1')
        }
        let uploadComplete = function (up, file) {
          console.log('uploadComplete1')
        }
        let fileUploaded = function (up, file, info) {
          console.log('uploaded')
          let domain = up.getOption('domain')
          let res = JSON.parse(info||'{}')
          let sourceLink = domain + (self.$store.state.isUseQiniu ? res.key : file.fileKey) // 获取上传成功后的文件的Url
          self.imgUrl = sourceLink + '?imageView2/1/w/900/h/500'
          let data = {
            url: sourceLink,
            _id: self.weixindata._id
          }
          self.$store.dispatch('saveWeixinMaterial', data).then((res) => {
            if (res.success) {
              self.imgTxtData.imgMediaId = res.media_id
              self.$message.success(self.$t('configLazyLoad.channel.wexinTip86'))
            }
          })
        }
        let error = function (up, err, errTip) {
          if (errTip) {
            self.$message.error(errTip)
          }
          console.log('uploadError ' + errTip)
        }
        let key = function (up, file) {
          let date = getCurrentDate()
          let today = new Date()
          let time = today.getTime()
          let fileName = file.name
          let fileSuffix = ''
          if (fileName) {
            fileSuffix = fileName.substring(fileName.lastIndexOf('.'), fileName.length)
          }
          let key = account + '/km/' + date + '/' + time + '/' + uuid.v1() + fileSuffix
          return key
        }
        let filters = {
          mime_types: [
            {title: 'Image files', extensions: 'jpg,png'}
          ]
        }
        this.m7uploaders.push(
          uploadTo7moorImDomain(this.$store.state.session.user._id, 'WechatMenuImageFile', filters, fileAdded, beforeUpload, uploadProgress, uploadComplete, fileUploaded, error, key)
        )
      }
    },
    mounted () {
      let editor = new Editor('#weixinEdit')
      editor.config.menus = [
        'head',
        'bold',
        'fontSize',  // 字号
        'fontName',  // 字体
        'foreColor',  // 文字颜色
        'backColor',
        'italic',
        'underline',
        'justify'  // 对齐方式
      ]
      editor.config.pasteTextHandle = filterXSS
      editor.config.fontNames = [ '微软雅黑', '宋体', '新宋体', '仿宋', '楷体', '黑体', 'Arial', 'Arial Black', 'Times New Roman', 'Courier New', 'Tahoma', 'Verdana' ]
      let lang = window.langJson || {}
      let editLang = lang.wangeditor
      editor.config.lang = editLang
      editor.config.onchange = (html) => {
        this.imgTxtData.content = editor.txt.html()
        this.trimTxt = editor.txt.text()
      }
      editor.config.zIndex = 1
      editor.create()
      this.initUploadImageFile()
      if (!isEmptyObj(this.imgdata)) {
        let data = deepClone(this.imgdata)
        this.imgUrl = data.url
        this.imgTxtData.imgMediaId = data.thumb_media_id
        this.imgTxtData.title = data.title
        this.imgTxtData.author = data.author
        this.imgTxtData.content = data.content
        this.imgTxtData.content_source_url = data.content_source_url
        this.imgTxtData.digest = data.digest
        this.imgTxtData.show_cover_pic = data.show_cover_pic
        this.imgTxtData.thumb_media_id = data.thumb_media_id
        editor.txt.html(filterXSS(this.imgTxtData.content))
      }
    },
    beforeDestroy () {
      this.m7uploaders.forEach(uploader => {
        uploader &&
        uploader.destroy &&
        uploader.destroy()
      })
    }
  }
</script>

<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .MenuEdit
    height 600px
    overflow-y auto
    overflow-x hidden
    padding-right 3px
    #weixinEdit
      min-height 150px
    .w-e-text-container
      height: 150px!important
    .secondArea
      background: #F2F2F2;
      border-top: 1px solid $c-border2;
      padding: 0 30px 30px 30px ;
      margin: 20px -20px 0 -20px;
      h3
        font-weight: bold;
        margin: 20px 0;
      .pictips
        color: $cf-gray4;
      .uploadImg
        border-radius: 0 !important;
        width: 100px;
        height: 100px;
        display: inline-block;
        background: $cf-level3;
      .deleteImg
        color: $btn-color
        margin-left 20px
        cursor pointer
    .footer
      text-align center
      margin:10px 0
</style>
